﻿Imports Newtonsoft.Json.Linq
Public Class objFindGroup
    Public GroupName As String
    Public GroupId As Long
    Public MemberCount As Integer
    Public Offset As Integer = 0
    Public Limit As Integer = 50
    Public Processing As Boolean = False
End Class

Public Class clsGroupFindByAPI
    Dim frm As frmMain
    Dim info As objFindGroup
    Dim ParseHTML As New clsParseHTML
    Dim Callback As Action(Of Integer, frmMain)
    Public Sub New(ByRef frmMain As frmMain, ByRef infoFind As objFindGroup, ByRef cback As Action(Of Integer, frmMain))
        frm = frmMain
        info = infoFind
        Callback = cback
    End Sub

    Public Sub find()
        Dim GroupList As String = ParseHTML.getURL("https://graph.facebook.com/search?offset=" & info.Offset & "&limit=" & info.Limit & "&type=group&q=" & info.GroupName & "&access_token=" & frm.Account.Login.infoLogin.AccessToken)
        If (GroupList <> "") Then
            Dim jGroupList As JObject = JObject.Parse(GroupList)
            Dim arrGroupList = jGroupList.SelectToken("data")
            Dim i As Integer = 0
            For i = 0 To arrGroupList.Count - 1
                Dim obj As New objFindGroup
                obj.GroupName = arrGroupList(i).SelectToken("name").ToString
                obj.GroupId = arrGroupList(i).SelectToken("id").ToString

                Dim GroupDetail As String = ParseHTML.getURL("https://graph.facebook.com/" & obj.GroupId & "?fields=members&access_token=" & frm.Account.Login.infoLogin.AccessToken)
                Dim jGroupDetail As JObject = JObject.Parse(GroupDetail)
                If (jGroupDetail.SelectToken("members") IsNot Nothing) Then
                    Dim jGroupMember = jGroupDetail.SelectToken("members")
                    If (jGroupMember.Count > 0) Then
                        obj.MemberCount = jGroupMember.SelectToken("data").Count
                    Else
                        obj.MemberCount = 0
                    End If
                Else
                    obj.MemberCount = 0
                End If

                If (obj.MemberCount > info.MemberCount) Then
                    If (frm.GroupFB.GroupFindResult.ContainsKey(obj.GroupId) = False) Then
                        frm.GroupFB.GroupFindResult.Add(obj.GroupId, obj)
                        With frm.lstFindGroup.Items.Add(frm.lstFindGroup.Items.Count + 1)
                            .SubItems.Add(obj.GroupName)
                            .SubItems.Add(obj.MemberCount)
                        End With
                    End If
                End If
            Next
            Callback(1, frm)
        Else
            Callback(0, frm)
        End If
    End Sub
End Class
